package demo2接口使用案例;

import java.util.Arrays;
import java.util.Comparator;

//另一种比较方式Comparator,这种也叫做比较器，两者可以共同实现,互不干扰
//有点：对类的侵入性不强
class Student2 implements Comparable<Student2>{
    public String name;
    public int age;

    @Override
    public int compareTo(Student2 o) {
        return this.age - o.age;
    }

    public Student2(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
//这时候我就需要再建一个类就行了
class AgeComparator implements Comparator<Student2>{
    @Override
    public int compare(Student2 o1, Student2 o2) {
        return o1.age - o2.age;
    }
}
class NameComparator implements Comparator<Student2>{
    @Override
    public int compare(Student2 o1, Student2 o2) {
        return o1.name.compareTo(o2.name);
        //name是引用类型，不能进行相减来进行比较，但是我们发现了String类中也有去实现Comparable的方法
        //所以我们只需要重写compareTo方法即可
    }
}
public class Test2 {
    public static void main(String[] args) {
        Student2 student1 = new Student2("zhangsan", 10);
        Student2 student2 = new Student2("lisi", 15);
        AgeComparator ageComparator = new AgeComparator();
        System.out.println(ageComparator.compare(student1, student2));
        //这个时候我们打印的是-5，前者减去后者
        System.out.println("==========");

        NameComparator nameComparator = new NameComparator();
        System.out.println(nameComparator.compare(student1, student2));

        System.out.println("==========");

        Student[] students = new Student[3];
        students[0] = new Student("zhangsan",10);
        students[1] = new Student("lisi",2);
        students[2] = new Student("niulianqiang",18);
        Arrays.sort(students);//这个时候要用comparable来进行一定的顺序排序，
        //因为通过comparable来进行查找一定的内容，从而按一定的内容来进行排序了
        System.out.println(Arrays.toString(students));
    }
}
